using System;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;
using Voodoo.Sauce.Internal;
using Voodoo.Sauce.Internal.IAP;

namespace Voodoo.Sauce.Components
{
	[RequireComponent(typeof(Button))]
	[AddComponentMenu("VoodooSauce/No Ads Button")]
	public class NoAdsButton : MonoBehaviour, IPurchaseDelegate
	{
		private const string TAG = "NoAdsButton";

		private string _noAdsBundleId;

		private Button _button;

		private void Start()
		{
			_button = GetComponent<Button>();
			VoodooSettings voodooSettings = Resources.Load<VoodooSettings>("VoodooSettings");
			if (voodooSettings == null)
			{
				throw new Exception("[NoAdsButton] Couldn't find VoodooSettings.");
			}
			_noAdsBundleId = voodooSettings.NoAdsBundleId;
			if (string.IsNullOrEmpty(voodooSettings.NoAdsBundleId))
			{
				throw new Exception("[NoAdsButton] You'll need to fill the 'No Ads Bundle Id' in order to use this component.");
			}
			_button.onClick.AddListener(PurchaseNoAds);
			_button.interactable = false;
			VoodooSauce.RegisterPurchaseDelegate(this);
		}

		private void PurchaseNoAds()
		{
			VoodooLog.Log("NoAdsButton", "Purchasing no ads...");
			VoodooSauce.Purchase(_noAdsBundleId);
		}

		public void OnInitializeSuccess()
		{
			VoodooLog.Log("NoAdsButton", $"Store has been initialized, ready to purchase no-ads. Is Premium: {VoodooPremium.IsPremium()}");
			_button.interactable = !VoodooPremium.IsPremium();
		}

		//public void OnInitializeFailure(InitializationFailureReason reason)
		//{
		//	VoodooLog.Log("NoAdsButton", $"Error while initializing store: {reason}");
		//}

		public void OnPurchaseComplete(string productId)
		{
			if (productId == _noAdsBundleId)
			{
				VoodooLog.Log("NoAdsButton", "No ads purchased!");
				VoodooPremium.EnablePremium();
				_button.interactable = false;
			}
		}

		//public void OnPurchaseFailure(string productId, PurchaseFailureReason reason)
		//{
		//	if (productId == _noAdsBundleId)
		//	{
		//		VoodooLog.LogW("NoAdsButton", $"Error while purchasing no-ads. Bundle id provided: {productId}, reason: {reason}");
		//	}
		//}
	}
}
